import uiautomator2 as u2
import time
from datetime import datetime
import random
import uiautomator2

shour = int(input("请输入上吧小时: "))
smin = int(input("请输入上吧分钟: "))
ehour = int(input("请输入下吧小时: "))
emin = int(input("请输入下吧分钟: "))
deviation = int(input("设定时间偏差分钟: "))

old_time = 0
current_timestamp = time.time()

while True:
    # 获取当前时间  
    now = datetime.now()  
    
    # 获取当前的小时和分钟  
    current_hour = now.hour  
    current_minute = now.minute
    deviation_min = deviation
    
    # print(current_hour,shour,current_minute,(smin + deviation_min))
    # print(current_hour,ehour,current_minute,(emin + deviation_min))
    # print(smin,emin,deviation_min)
    current_timestamp = time.time()
    try:
        if ((current_hour == shour and current_minute == (smin + deviation_min)) or (current_hour == ehour and current_minute == (emin + deviation_min))) and current_timestamp - old_time > deviation*60:
            # 获取当前Unix时间戳（秒）  
            old_time = time.time()
            print(old_time)
            print(datetime.now())
            phone_device = u2.connect() #打开USB连接手机.
            time.sleep(3)
            phone_device = u2.connect() #打开USB连接手机.
            time.sleep(3)
            phone_device = u2.connect() #打开USB连接手机.
            time.sleep(2)
            phone_device.press("home")
            time.sleep(2)
            exists = phone_device(text="钉钉").wait(timeout=3)  # 等待最多10秒  
            if exists:  
                phone_device(text = "钉钉").click()
            time.sleep(5)
            exists = phone_device(text="暂不打卡").wait(timeout=3)  # 等待最多10秒  
            if exists:  
                phone_device(text = "暂不打卡").click()
            time.sleep(2)
            exists = phone_device(text="工作台").wait(timeout=3)  # 等待最多10秒  
            if exists:  
                phone_device(text = "工作台").click()
            time.sleep(2)

            exists = phone_device(text="考勤打卡").wait(timeout=3)  # 等待最多10秒  
            if exists:  
                phone_device(text = "考勤打卡").click()
            
            # 点击考勤打卡
            action = phone_device.click(130, 1020)
            time.sleep(5)
            # 点击打卡
            action = phone_device.click(540, 1330)
            time.sleep(5)
            phone_device.press("back")
            time.sleep(2)
            phone_device.press("home")
            #打完一次卡以后,随机时间修改
            deviation_min = random.randint(0, deviation)
    except Exception as e:  
        print(f"An exception occurred: {e}")
        # print("数据错误!!!")
        break
        
    time.sleep(2)
    
while True:
    time.sleep(2)
    
# time.sleep(2)
# phone_device(text = "上班打卡").click()
# time.sleep(2)
# phone_device(text = "下班打卡").click()
